package com.heima.comment.service.impl;

import com.heima.comment.fegin.ApUserFegin;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author feng js
 */
@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto.getCommentId() == null || dto.getMinDate() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size = 10;
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime")
                .lt(dto.getMinDate())).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            //没有登录时，直接展示评论
            return ResponseResult.okResult(apCommentRepays);
        }
        List<ApCommentRepayVo> resultList = new ArrayList<>();
        List<String> repaysIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentRepayId").in(repaysIds));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        if (apCommentRepayLikes.size()> 0 ) {
            apCommentRepays.stream().forEach(apCommentRepay -> {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(apCommentRepay,apCommentRepayVo);
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if (apCommentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                        apCommentRepayVo.setOperation((short) 0);
                    }
                }
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        } else {
            return ResponseResult.okResult(apCommentRepays);
        }

    }
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private ApUserFegin apUserFegin;

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论字数过多");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            Map map = greenTextScan.greeTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if (suggestion.equals("block")||suggestion.equals("review")) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论审核不通过");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论审核不通过");
        }
        ApUser apUserFeginUser = apUserFegin.findUserById(user.getId());
        if (apUserFeginUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(apUserFeginUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        if (dto.getCommentRepayId() == null ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录，不登陆不能点赞
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay != null && dto.getOperation() == 0) {
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(apCommentRepay.getAuthorId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            mongoTemplate.save(apCommentRepayLike);
        } else if (apCommentRepay != null && dto.getOperation() == 1) {
            apCommentRepay.setLikes(apCommentRepay.getLikes()<=0?0:apCommentRepay.getLikes()-1);
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(apCommentRepay.getId())),ApCommentRepayLike.class);

        }
        Map<String, Object> map = new HashMap<>();
        map.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
